package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDates(begin, end);

        List<Double> dailyAmount = new ArrayList<>();
        dateList.forEach(date -> {
            Map map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
            Double amount = ordersMapper.getByStatusAndDay(map);
            dailyAmount.add(amount == null ? 0.0 : amount);
        });

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ','))
                .turnoverList(StringUtils.join(dailyAmount, ','))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDates(begin, end);

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> sumUserList = new ArrayList<>();

        dateList.forEach(date -> {
            Map map = new HashMap<>();
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
            Integer sumUser = userMapper.getUsersCount(map);
            sumUserList.add(sumUser);
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            Integer newUser = userMapper.getUsersCount(map);
            newUserList.add(newUser);
        });

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ','))
                .totalUserList(StringUtils.join(sumUserList, ','))
                .newUserList(StringUtils.join(newUserList, ','))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDates(begin, end);
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            Map totalAndValidOrder = ordersMapper.getTotalAndValidOrderCount(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            Long totalOrderCount = (Long) totalAndValidOrder.get("total");
            Long validOrderCount = (Long) totalAndValidOrder.get("valid");
            orderCountList.add(Math.toIntExact(totalOrderCount));
            validOrderCountList.add(Math.toIntExact(validOrderCount));
        }
        Integer totalOrderSum = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderSum = validOrderCountList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate = 0.0;
        if (totalOrderSum != 0) orderCompletionRate = validOrderSum.doubleValue() / totalOrderSum.doubleValue();
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ','))
                .orderCountList(StringUtils.join(orderCountList, ','))
                .validOrderCountList(StringUtils.join(orderCountList, ','))
                .totalOrderCount(Math.toIntExact(totalOrderSum))
                .validOrderCount(Math.toIntExact(validOrderSum))
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        Map requestMap = new HashMap<>();
        requestMap.put("status", Orders.COMPLETED);
        requestMap.put("begin", LocalDateTime.of(begin, LocalTime.MIN));
        requestMap.put("end", LocalDateTime.of(end, LocalTime.MAX));
        List<Map> result = ordersMapper.top10(requestMap);

        String nameList = result.stream().map(v -> v.get("name").toString()).collect(Collectors.joining(","));
        String numberList = result.stream().map(v -> v.get("number").toString()).collect(Collectors.joining(","));

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }


    private static List<LocalDate> getDates(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        while (begin.isBefore(end) || begin.isEqual(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        log.info(dateList.toString());
        return dateList;
    }
}
